package fiz.pkg;

public class PolySolver {
	
	public static String solve(String[] args){
		double A, B, C;
		String[] tempArray = new String[3];
		
		//Ensure that there are three arguments
		for(int i = 0; i < 3; i++){
			try{
				tempArray[i] = args[i];
			} catch (Exception e) {
				tempArray[i] = "0";
			}
		}
		args = tempArray;
		
		//Parse floats from arguments
		try{
			A = Double.parseDouble(args[0]);
			B = Double.parseDouble(args[1]);
			C = Double.parseDouble(args[2]);
		} catch (Exception e) {
			return "Arguments must be real numbers";
		}
		
		//Check conditions and calculate
		if(Double.isInfinite(A) || Double.isInfinite(B) || Double.isInfinite(C)) return "One or more numbers are out of bounds";
		if(A == 0 && B == 0 && C == 0) return "Infinitely many solutions";
		else if(A == 0 && B == 0 && C != 0) return "No solution";
		else if((A == 0 || B == 0) && C == 0) return "0.0";
		else if(A == 0) return String.valueOf(-C/B);
		else return quadraticFormula(A, B, C);
	}
	
	private static String quadraticFormula(double A, double B, double C){
		double partOne, partTwo;
		String result;
		
		partOne = -B/(2*A);
		partTwo = Math.sqrt((B*B)-(4*A*C))/(2*A);
		
		//If result is imaginary
		if(Double.isNaN(partTwo)){
			partTwo = Math.sqrt(-1*((B*B)-(4*A*C)))/(2*A);
			if(partOne != 0)
				result = partOne + "+" + partTwo + "i, " + partOne + "-" + partTwo + "i";
			else
				result = partTwo + "i, " + -partTwo + "i";
		}
		else{
			result = (partOne+partTwo) + ", " + (partOne-partTwo);
		}
		
		//Check if result is too large
		if(Double.isInfinite(partOne) || Double.isInfinite(partTwo) || Double.isNaN(partOne) || Double.isNaN(partTwo))
			return "The result is too large to store";
		
		return result;
	}
}
